<template>
  <!--关注组件开始 -->
  <!-- 由于这里v-if和v-else的缘故;这里就算外部不用div包裹也行 -->
  <van-button
    v-if="isFollowed"
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    @click="onFollow"
    :loading="loading"
  >
    关注
  </van-button>

  <van-button
    v-else
    class="follow-btn"
    round
    size="small"
    @click="onFollow"
    :loading="loading"
  >
    已关注
  </van-button>
  <!--关注组件接收 -->
</template>

<script>
// 关注接口
import { addFollow, deleteFollow } from "@/api/user";
export default {
  name: "FollowUser",
  props: {
    // 传过来用来判断状态
    isFollowed: {
      type: Boolean,
      required: true,
    },
    userId: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      loading: false, // ``按钮内部加载状态`` 状态显示与否
    };
  },

  methods: {
    // 关注和取消关注
    async onFollow() {
      // 显示加载方法loading
      this.loading = true;
      try {
        if (this.isFollowed) {
          // 已关注，取消关注
          await deleteFollow(this.userId);
        } else {
          await addFollow(this.userId);
        }
        // this.article.is_followed = !this.article.is_followed;
        // 跟新本地状态的话使用``子传父``和上面if或者else的状态相反
        this.$emit("update-is_followed", !this.isFollowed);
      } catch (error) {
        let message = "操作失败，请重试";
        if (error.response && error.response.status === 400) {
          message = "你不能关注你自己！";
        }
        this.$toast(message);
      }
      // 关闭加载方法loading
      this.loading = false;
    },
  },
};
</script>

<style lang="less" scoped></style>
